#include "threadpool.h"
#include"log.h"
#include"mySql.h"

void threadpoolInit(thread_pool_t* pthreadpool,int threadNum){
    pthreadpool->threadNum = threadNum;
    pthreadpool->threads =(pthread_t*)calloc(threadNum,sizeof(pthread_t));
    queueInit(&pthreadpool->queue);    
}

void threadpoolDestroy(thread_pool_t*pthreadpool){
    free(pthreadpool->threads);
    queueDestory(&pthreadpool->queue);
}

void threadpoolStart(thread_pool_t*pthreadpool){
    for(int idx=0;idx<pthreadpool->threadNum;++idx){
        int ret = pthread_create(&pthreadpool->threads[idx],
                                 NULL,
                                 threadFunc,
                                 pthreadpool);
        THREAD_ERROR_CHECK(ret,"pthread_create");

    }
}
void * threadFunc(void * arg){
    printf("sub thread %ld is runing\n", pthread_self());
    thread_pool_t * pthreadpool = (thread_pool_t*)arg;

    while(1) {
        int peerfd = taskDequeue(&pthreadpool->queue);
        if(peerfd > 0) {
            /* char filename[] = "bigfile.avi";
               transferFile(peerfd, filename);*/
            handlEvent(peerfd);

            //日志记录
            char logbuff[100]="handlEvent";
            writelog(logbuff);

        } else {
            break;
        }
    }
    printf("sub thread %ld is ready to exit\n", pthread_self());
    pthread_exit(0);

}
void handlEvent(int peerfd){
    int epfd = epollCreat();
    struct epoll_event evt[2];
    MYSQL*mysql = connectMysql();//连接数据库
    //日志记录
    char logbuff[100]="mysql is conn!";
    writelog(logbuff);

    //每次进入时，都是进入服务器的serverFile文件里面
    char cd[100]="serverFile";
    cd1(cd);    
    char username[20]={0};//接收服务器端发来的名字去掉\n
    char id[10]={0};//记录username用户对应的id
    char md5[100]={0};

    while(1){
        int uret = epoll_wait(epfd, evt, MAXCONNS, 1000);
        MYSQL_RES *res;//SQL执行结果
        MYSQL_ROW row;//保存行数据
        char query[1024] = {0};//sql语句执行数据
        char cryptpasswd[20]={0};//接收服务端密文
        char sqlSalt[100]={0};//数据库中用户对应的盐值
        char sqlCryptpasswd[100]={0};//数据库中用户对应的密文

        //接收客户端发来的姓名
        memset(username,0,sizeof(username));
        printf("username is:%s\n",username);
        trainRecv(username,peerfd);
        if(username[0] == '\0'){
            //日志记录
            char logbuff[100]="client is exit!";
            writelog(logbuff);
            break;
        }

        //判断用户是否存在
        sprintf(query,"select username from user where username = '%s';",username);
        printf("登录查询:query is %s\n",query);

        handlQuery(mysql,query,peerfd);
        res = mysql_store_result(mysql);
        if((row = mysql_fetch_row(res))==NULL){//不存在
            printf("enter failname\n");
            char failName[20]="failname";
            trainSend(failName,peerfd);

            //接收服务端指令，看是否进行注册
            char r[2]={0};
            trainRecv(r,peerfd);
            printf("--r is:%s\n",r);
            if(r[0] == '\0'){
                //日志记录
                char logbuff[100]="client is exit!";
                writelog(logbuff);
                break;
            }
            else if(memcmp(r,"1",strlen(r))==0){
                printf("---enter register-\n");
                printf("---enter recvSaltCryptpasswd\n");
                userRegister(mysql,peerfd,id);
                //日志记录
                char logbuff[100]={0};
                sprintf(logbuff,"user %s is register!",username);
                writelog(logbuff);
                printf("---enter userRegister\n");
            }
            continue;
        }else{//用户存在
            char failName[20]="failname is true";
            trainSend(failName,peerfd);

            //取出数据库中对应用户的盐值和密文
            recvSaltCryptpasswd(mysql,sqlSalt,
                                sqlCryptpasswd,username,id);
            //发送盐值过去
            trainSend(sqlSalt,peerfd);

            //接收服务端密文
            trainRecv(cryptpasswd,peerfd);

            //进行密文对比
            //为0登录成功
            //否则失败
            if(strcmp(sqlCryptpasswd ,cryptpasswd)==0){
                printf("------------------------------\n");
                printf("user log in\n");
                char success[20]="success";
                trainSend(success,peerfd);
                //日志记录
                char logbuff[100]={0};
                sprintf(logbuff,"user %s is log in!",username);
                writelog(logbuff);
                break;
            }else{
                printf("------------------------------\n");
                printf("passwd error\n");
                char fail[20]="fail";
                trainSend(fail,peerfd);
                //日志记录
                char logbuff[100]={0};
                sprintf(logbuff,"user %s is not log in!",username);
                writelog(logbuff);
                continue;
            }
        }
    }

    int parent_id = 0;
    while(1){
        int nret = epoll_wait(epfd, evt, MAXCONNS, 1000);
        char recvbuff[BUFFSIZE] = {0};//接收文件数组
        char order[100]={0};//指令数组
        char filename[100]={0};//文件名数组
        char logbuff[100] = {0};//日志数组
        int owner_id = atoi(id);



        printf(">>>>ower_id is:%d\n",owner_id);
        printf(">>>>username:%s\n",username);

        //接受文件
        int length;
        int ret = recv(peerfd,&length,4,MSG_WAITALL);

        printf(">recvbuff length is %d\n",length);

        ret = recv(peerfd, recvbuff, length, MSG_WAITALL);

        printf(">>1. recvbuff:%s\n",recvbuff);

        if(0 == ret){
            break;
        }

        if(strncmp(recvbuff,"ls",2)==0){
            printf("recvbuff %s aa\n",recvbuff);
            //日志记录
            char logbuff[100]={0};
            sprintf(logbuff,"order is :ls! username is:%s",filename);
            writelog(logbuff);
            //ls(peerfd);
            ls_3th(mysql,username,parent_id,peerfd);
        }/*else if(strncmp(recvbuff,"pwd",3)==0){
           printf("enter srtncmp :%s \n",recvbuff);
           pwd(peerfd);
           }*/else if(strncmp(recvbuff,"gets",4)==0){
               //日志记录
               char logbuff[100]={0};
               sprintf(logbuff,"order is :gets! usename is:%s",filename);
               writelog(logbuff);

               printf("--enter train gets\n");
               splitChar(recvbuff,order,filename);

               char a[5]={0};
               trainRecv(a,peerfd);
               printf("puts a is:%s\n",a);
               if(memcmp(a,"5",strlen(a))==0){
                   continue;
               }else{
                   trainSend(recvbuff,peerfd);

                   printf("trainSend recvbuff %s\n",recvbuff);
                   //do_gets(peerfd,filename);
                   do_gets_3th(mysql,username,filename,parent_id,
                               owner_id,peerfd);
                   continue;
               }

               trainSend(recvbuff,peerfd);

               printf("trainSend recvbuff %s\n",recvbuff);
               //do_gets(peerfd,filename);
               do_gets_3th(mysql,username,filename,parent_id,
                           owner_id,peerfd);
           }
        else{
            splitChar(recvbuff,order,filename);
            parent_id = judge(order,filename,peerfd,
                              mysql,parent_id,username,
                              owner_id);
            printf(">parent_id is:%d\n",parent_id);
        }
        /*if(strcmp(order,"rm") == 0){
          printf(">order have rm\n");
          rm(filename,peerfd);
          }*/

        //发送文件给客户端
        // ret = sendn(peerfd,recvbuff,strlen(recvbuff));
        memset(&recvbuff,0,sizeof(recvbuff));
        memset(&order,0,sizeof(order));
        memset(&filename,0,sizeof(filename));
    }
    mysql_close(mysql);//关闭数据库
    //日志记录
    char logbuff1[100]="close mysql";
    writelog(logbuff1);
}
